import request from '@/utils/request'
import { RootThunkAction } from '..'
import { SearchAction } from '../reducers/search'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage'
import { Article } from '../reducers/home'

/**
 * 获取推荐列表
 * 
 */
type SuggestListRes = {
    options: string[]
}
export function getSuggestList(keyword: string): RootThunkAction {
    return async (dispatch) => {
        // axios.request<T>()  axios.get<T>() axios.post<T>()
        // T默认是any类型，用于指定data的类型
        // 如何给axios指定泛型
        // request.get<>()
        // axios.post<T>()
        const res = await request.get<SuggestListRes>('/suggestion?q=' + keyword)
        // 后台搜索 结果如果没有数据，返回的结果为[null],遍历就会报错，所以如果是这种情况，默认为[]
        let options = res.data.options
        if (!options[0]) {
            options = []
        }
        dispatch({
            type: 'search/saveSuggestions',
            payload: options
        })
    }
}

export function clearSuggestions(): SearchAction {
    return {
        type: 'search/clearSuggestions',
    }
}

export function addSearchList(keyword: string): RootThunkAction {
    return async (dispatch, getState) => {
        // 获取到原来的histories
        let histories = getState().search.histories
        // 1. 不允许有重复的历史记录
        histories = histories.filter(item => item !== keyword)
        // 添加keyword
        histories = [keyword, ...histories]
        if (histories.length > 10) {
            histories = histories.slice(0, 10)
        }
        // 保存
        dispatch({
            type: 'search/saveHistories',
            payload: histories
        })
        // 保存到本地
        setLocalHistories(histories)
    }
}

/**
 * 清空历史记录
 * @returns 
 */
export function clearHistories(): RootThunkAction {
    return async (dispatch) => {
        // 清空本地的历史记录
        removeLocalHistories()
        // 清空redux数据
        dispatch({
            type: 'search/clearHistories'
        })
    }
}

type Results = {
    page: number
    per_page: number
    results: Article[]
    total_count: number
}
/**
 * 获取搜索结果数据
 * 
 */
export function getSearchResults(keyword: string, page: number): RootThunkAction {
    return async (dispatch) => {
        const res = await request.get<Results>('search', {
            params: {
                q: keyword,
                page,
                per_page: 10
            }
        })
        dispatch({
            type: 'search/saveResults',
            payload: res.data.results
        })
    }
}